import { RequestOption } from './baseAjaxService';
import * as fetch from 'isomorphic-fetch';
import 'rxjs';
import { Observable } from "rxjs/Observable"

export interface RequestOption {
    url: string
    method: string
    option?: any
}

function cFetch(url, method = "GET", option) {
    const defaultOpts = {
        //mode: 'cors',
        //credentials: 'include'
    }
    const opts = { ...option, method: method, ...defaultOpts };
    opts.headers = {
        ...option.headers,
        "Content-Type": "application/json"
    }

    console.log("ajax opts:", opts);
    return fetch(url, opts)
        .then(response =>
            response.json().then(json => ({ json, response }))
        ).then(({ json, response}) => {
            console.log("response:", response);
            if (!response.ok) {
                return Promise.reject({...json, url:response.url});
            }

            return {...json, url: response.url};
        }).then(
        response => ({ response }),
        error => ({ ...error })
        )
}

function batchFetch(options: RequestOption[]) {
    let requests: Promise<any>[] = []
    options.forEach((requestOption: RequestOption) => {
        const promise = cFetch(requestOption.url, requestOption.method, requestOption.option);
        requests.push(promise);
    });
    //let requestOption = options[0]
    return Observable.forkJoin(requests).toPromise()
        .then((response:any) => {
            let changedResponse =  response.map((obj) => {
                if(obj.error === undefined) {
                    obj["hasError"] = false;
                } else {
                    obj["hasError"] = true;
                }
                return obj;
            })
            return changedResponse;
        }).then(
                response => ({ response }),
                error => ({ ...error }))
        .catch(error => {
            return Promise.reject({ error })
        })


    /* .subscribe(results => {
         console.log("merger results:", results)
     });*/
    //return cFetch(requestOption.url, requestOption.method, requestOption.option);
}


export default batchFetch;
